<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, Plus, Search, Refresh, User } from "@element-plus/icons-vue";
import UserForm from "./modules/userForm.vue";
import { getAdminList, deleteAdmin } from "@/api/admin";
import { formatDate } from "../../../utils/format";
import { getRoleList } from "@/api/role";
import type { Role } from "@/api/role";

defineOptions({
  name: "UserManagement"
});

interface UserType {
  id: number;
  username: string;
  nickname: string;
  avatar: string;
  password: string;
  phone: string;
  status: number;
  role_id: number;
  role_name: string;
  created_at: number;
  update_time: number;
}

// 表格数据
const tableData = ref<UserType[]>([]);
const loading = ref(false);
const searchForm = reactive({
  keyword: "",
  status: ""
});

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 弹窗控制
const userFormVisible = ref(false);
const formType = ref("add");
const currentUser = ref<Partial<UserType>>({});

// 角色数据
const roleOptions = ref<Role[]>([]);

// 获取角色列表
const getRoles = async () => {
  try {
    const res = await getRoleList({
      page: 1,
      pageSize: 999 // 获取所有角色
    });
    if (res.code === 0) {
      roleOptions.value = res.data.list;
    } else {
      ElMessage.error(res.msg || "获取角色列表失败");
    }
  } catch (error) {
    console.error("获取角色列表出错:", error);
    ElMessage.error("获取角色列表失败");
  }
};

// 获取用户列表
const getUserList = async () => {
  loading.value = true;
  try {
    const res = await getAdminList({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status ? parseInt(searchForm.status) : undefined
    });

    if (res.code === 0) {
      tableData.value = res.data.list;
      pagination.total = res.data.total;
    } else {
      ElMessage.error(res.msg || "获取管理员列表失败");
    }
  } catch (error) {
    console.error("获取管理员列表出错:", error);
    ElMessage.error("获取管理员列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  getUserList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = "";
  searchForm.status = "";
  handleSearch();
};

// 打开弹窗
const openDialog = async (type: string, row?: UserType) => {
  // 确保角色列表已加载
  if (roleOptions.value.length === 0) {
    await getRoles();
  }

  // 重置当前用户对象，避免数据污染
  currentUser.value = {};

  // 设置表单类型
  formType.value = type;

  // 根据类型设置初始值
  if (type === "add") {
    currentUser.value = {
      status: 1,
      role_id: 0
    };
  } else if (row) {
    // 使用展开运算符创建一个新对象，避免引用原对象
    currentUser.value = { ...row };
  }

  // 最后打开弹窗
  userFormVisible.value = true;
};

// 保存用户
const handleSaveUser = (user: UserType) => {
  userFormVisible.value = false;
  // 重新加载列表
  getUserList();
  // 重置当前用户对象
  currentUser.value = {};
};

// 删除用户
const deleteUser = async (id: number) => {
  try {
    await ElMessageBox.confirm("确定要删除该管理员吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const { data } = await deleteAdmin(id);
    if (data.code === 0) {
      ElMessage.success("删除成功");
      getUserList();
    } else {
      ElMessage.error(data.msg || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除管理员出错:", error);
      ElMessage.error("删除管理员失败");
    }
  }
};

// 页码变更
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  getUserList();
};

// 每页数量变更
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  getUserList();
};

// 角色数据列显示
const getRoleName = (roleId: number): string => {
  if (!roleId) return '未分配';
  const role = roleOptions.value.find(role => role.id === roleId);
  return role ? role.name : '未知角色';
};

onMounted(() => {
  getUserList();
  getRoles(); // 获取角色列表
});
</script>

<template>
  <div>
    <!-- 搜索栏 -->
    <el-card class="search-container" shadow="never">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键字">
          <el-input v-model="searchForm.keyword" placeholder="用户名/昵称" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable style="width: 180px">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="table-container" shadow="never">
      <template #header>
        <div class="card-header">
          <span>管理员列表</span>
          <el-button type="primary" :icon="Plus" @click="openDialog('add')">添加管理员</el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column label="角色" min-width="120">
          <template #default="{ row }">
            <el-tag v-if="row.role_name">{{ row.role_name }}</el-tag>
            <el-tag v-else-if="row.role_id">
              {{ getRoleName(row.role_id) }}
            </el-tag>
            <el-tag v-else type="info">未分配</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="180">
          <template #default="{ row }">
            {{ row.created_at }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="openDialog('edit', row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="deleteUser(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>


      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 用户表单 -->
    <UserForm v-model:visible="userFormVisible" :user="currentUser" :type="formType" :role-options="roleOptions"
      @save="handleSaveUser" @update:visible="(val) => {
        userFormVisible = val;
        if (!val) currentUser = {};
      }" />
  </div>
</template>

<style scoped>
.search-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: end;
  margin-top: 20px;
}

.mx-1 {
  margin-right: 5px;
}
</style>